#include "drv_sht20.h"
#include "drv_iic.h"
#include "drv_systick.h"
#include "stdio.h"

sht20_val tem_hum_data;
void drv_sht20_init(void)
{
	drv_iic_init();
}

uint16_t drv_sht20_read(void)
{
	uint8_t data[2];
	uint16_t ret=0;
	drv_iic_start();
	drv_iic_senddata(0x80);
	if(drv_iic_waitACK()!=ACK)
	   {
		drv_iic_stop();
		return NOACK;
		}
	
	
	drv_iic_senddata(0xe3);
	if(drv_iic_waitACK()!=ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_iic_start();
	drv_iic_senddata(0x81);
	if(drv_iic_waitACK() !=ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_systick_ms(85);
	data[0] = drv_iic_readdata(ACK);
	data[1] = drv_iic_readdata(NOACK);
	drv_iic_stop();
	ret = ((data[0]<<8)|data[1]);
	printf("data[0]=%d data[1]=%d\r\n",data[0],data[1]);
	return ret;
}

uint16_t drv_sht20_read2(void)
{
	uint8_t data[2];
	uint16_t ret=0;
	drv_iic_start();
	drv_iic_senddata(0x80);
	if(drv_iic_waitACK()!=ACK)
	   {
		drv_iic_stop();
		return NOACK;
		}
	
	
	drv_iic_senddata(0xe5);
	if(drv_iic_waitACK()!=ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_iic_start();
	drv_iic_senddata(0x81);
	if(drv_iic_waitACK() !=ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_systick_ms(29);
	data[0] = drv_iic_readdata(ACK);
	data[1] = drv_iic_readdata(NOACK);
	drv_iic_stop();
	ret = ((data[0]<<8)|data[1]);
	printf("data[0]=%d data[1]=%d\r\n",data[0],data[1]);
	return ret;
}

uint8_t drv_sht20_rest(void)
{
		drv_iic_start();
		drv_iic_senddata(0x80);
		if(drv_iic_waitACK()!=ACK)
		   {
			drv_iic_stop();
			return NOACK;
			}
		drv_iic_senddata(0xfe);
		if(drv_iic_waitACK()!=ACK)
		{
			drv_iic_stop();
			return NOACK;
		}
		drv_iic_stop();
}


uint16_t drv_sht20_getdataT(void)
{	uint16_t temp=0;

	float st;
	
	uint16_t ret=0;
	
	temp = drv_sht20_read();
	
	tem_hum_data.tem = -46.85+175.72*((float)temp/65536);
	st = tem_hum_data.tem;
	ret = (uint16_t)(st*100.0f);
	printf("Temperature=%.2f\r\n",tem_hum_data.tem);
	return ret;
}

uint16_t drv_sht20_getdataH(void)
{	
	uint16_t Sr =0;
	float rt;
	

	uint16_t Hs=0;
	
	Sr = drv_sht20_read2();

	tem_hum_data.hum = -6+125*((float)Sr/65536);
	
	rt =tem_hum_data.hum;
	
	Hs =(uint16_t)(rt*100.0f);

	printf("SH=%.2f\r\n",tem_hum_data.hum);
	return Hs;
	
}
